package com.mmy.fta.trade.server.service.impl;

import com.mmy.fta.cargo.api.facade.CargoService;
import com.mmy.fta.cargo.api.model.CargoInfoDTO;
import com.mmy.fta.trade.server.dao.OrderDao;
import com.mmy.fta.trade.server.dao.OrderPayFlowDao;
import com.mmy.fta.trade.server.dto.CargoOrderDTO;
import com.mmy.fta.trade.server.entity.OrderPayFlowEntity;
import com.mmy.fta.trade.server.request.PayBackDepositRequest;
import com.mmy.fta.trade.server.request.PayCargoFeeRequest;
import com.mmy.fta.trade.server.request.PayDepositCheckRequest;
import com.mmy.fta.trade.server.request.PaymentRequest;
import com.mmy.fta.trade.server.request.PrePayCargoFeeRequest;
import com.mmy.fta.trade.server.request.PrePayDepositRequest;
import com.mmy.fta.trade.server.request.ReceiveOrderRequest;
import com.mmy.fta.trade.server.response.PayBackDepositResponse;
import com.mmy.fta.trade.server.response.PayCargoFeeResponse;
import com.mmy.fta.trade.server.response.PrePayCargoFeeResponse;
import com.mmy.fta.trade.server.response.PrePayDepositResponse;
import com.mmy.fta.trade.server.service.OrderService;
import com.mmy.fta.trade.server.service.PaymentService;
import com.mmy.fta.trade.server.util.SnowflakeIdUtils;
import com.mmy.fta.usercenter.api.CouponService;
import com.mmy.fta.usercenter.api.MembershipService;
import com.mmy.fta.usercenter.api.UserService;
import com.mmy.fta.usercenter.dto.DriverInterestsDTO;
import com.mmy.fta.usercenter.dto.ShipperInterestsDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.Objects;

/**
 * @author qiang.lin
 * @since 2021/10/29
 */
@Service
@Slf4j
public class PaymentServiceImpl implements PaymentService {
    @Reference
    UserService userService;

    @Reference
    CargoService cargoService;

    @Reference
    MembershipService membershipService;

    @Reference
    CouponService couponService;

    @Autowired
    OrderPayFlowDao orderPayFlowDao;

    @Autowired
    OrderDao orderDao;

    @Autowired
    OrderService orderService;


    /**
     *
     * @param prePayDepositRequest
     * @return
     */
    @Override
    public PrePayDepositResponse prePayDepositByDriver(PrePayDepositRequest prePayDepositRequest) {

        DriverInterestsDTO driverInterestsDTO = userService.queryDriverInterests(prePayDepositRequest.getOpenId()).getData();

        log.info("司机{}——driverInterestsDTO{}",prePayDepositRequest.getOpenId(),driverInterestsDTO.toString());

        PrePayDepositResponse prePayDepositResponse = new PrePayDepositResponse();

        BeanUtils.copyProperties(driverInterestsDTO,prePayDepositResponse);

        CargoOrderDTO cargoOrderDTO= new CargoOrderDTO();
        CargoInfoDTO cargoInfoDTO = cargoService.queryCargoInfobyCargoId(prePayDepositRequest.getCargoId());
        BeanUtils.copyProperties(cargoInfoDTO,cargoOrderDTO);
        prePayDepositResponse.setCargoOrderDTO(cargoOrderDTO);

        //todo
        String pageId =  String.valueOf(new SnowflakeIdUtils(1, 1).nextId());
        prePayDepositResponse.setPageId(pageId);

        return prePayDepositResponse;
    }

    private boolean checkNetDeposit(Integer ndWeb, Integer ndCa){
        if(ndWeb.equals(ndCa)){
            return true;
        }else {
            return false;
        }

    }
    @Override
    public boolean payDepositCheckForDriver(PayDepositCheckRequest pdr,CargoInfoDTO cargoInfoDTO) {

        Integer deposit = cargoInfoDTO.getDeposit();
        //抽佣
        Integer estimateDistance = cargoInfoDTO.getEstimateDistance();
        //0-不退
        Integer  needReturnDeposit = cargoInfoDTO.getNeedReturnDeposit();
        Integer cargoFee = cargoInfoDTO.getCargoFee();


        if(pdr.getPreferenceType() == 1 && needReturnDeposit == 0){
            //免抽佣 不退
            Integer nd = cargoFee - deposit;
            if(checkNetDeposit(pdr.getNetDeposit(),nd)){
                //免拥-1
                membershipService.useFreeTime(pdr.getOpenId());
                return true;
            }else {
                return false;
            }
        }else if (pdr.getPreferenceType() == 2 && needReturnDeposit == 0 ){
            //货运券  不退

            Integer couponAmount = new Double(couponService.queryCouponAmount(Long.valueOf(pdr.getCouponId()))).intValue() ;
            if(couponAmount >= estimateDistance){
                //货>拥
                Integer nd = cargoFee - deposit;

                if(checkNetDeposit(pdr.getNetDeposit(),nd)){
                    //券-1
                    couponService.useCoupon(Long.valueOf(pdr.getCouponId()));
                    return true;
                }else {
                    return false;
                }
            }else {
                //货<拥
                Integer nd = cargoFee - deposit - estimateDistance + couponAmount;
                if(checkNetDeposit(pdr.getNetDeposit(),nd)){
                    //券-1
                    couponService.useCoupon(Long.valueOf(pdr.getCouponId()));
                    return true;
                }else {
                    return  false;
                }
            }

        }else if (pdr.getPreferenceType() == 3 && needReturnDeposit == 0 ){
            //不使用 不退
            Integer nd = cargoFee - deposit - estimateDistance;
            if(checkNetDeposit(pdr.getNetDeposit(),nd)){
                return true;
            }else {
                return false;
            }
        }else if (pdr.getPreferenceType() == 1 && needReturnDeposit == 1 ){
            //免拥 退
            Integer nd = cargoFee;
            if(checkNetDeposit(pdr.getNetDeposit(),nd)){
                //免佣-1
                membershipService.useFreeTime(pdr.getOpenId());
                return true;
            }else {
                return false;
            }
        }else if (pdr.getPreferenceType() == 2 && needReturnDeposit == 1 ) {
            //货 退
            Integer couponAmount = new Double(couponService.queryCouponAmount(Long.valueOf(pdr.getCouponId()))).intValue() ;
            if (couponAmount >= estimateDistance) {
                //货>拥
                Integer nd = cargoFee;

                if (checkNetDeposit(pdr.getNetDeposit(), nd)) {
                    //券-1
                    couponService.useCoupon(Long.valueOf(pdr.getCouponId()));
                    return true;
                } else {
                    return false;
                }
            } else {
                //货<拥
                Integer nd = cargoFee - estimateDistance + couponAmount;
                if (checkNetDeposit(pdr.getNetDeposit(), nd)) {
                    //券-1
                    couponService.useCoupon(Long.valueOf(pdr.getCouponId()));
                    return true;
                } else {
                    return false;
                }
            }
        }else {
            //不使用 退
            Integer nd = cargoFee  - estimateDistance;
            if(checkNetDeposit(pdr.getNetDeposit(),nd)){
                return true;
            }else {
                return false;
            }
        }
    }

    @Override
    public PayBackDepositResponse payBackDepositByShipper(PayBackDepositRequest payBackDepositRequest) {
        return null;
    }

    /**
     * 司机支付订金-流水
     * @param payId
     * @param driverOpenId
     * @param orderNumber
     * @param deposit
     * @return
     */
    @Override
    public int payDepositByDriver(String payId, String driverOpenId, String orderNumber, Integer deposit) {
        OrderPayFlowEntity orderPayFlowEntity =new OrderPayFlowEntity();


        orderPayFlowEntity.setPayId(payId);
        orderPayFlowEntity.setOrderId(orderNumber);
        orderPayFlowEntity.setFeeType(1);

        orderPayFlowEntity.setPayerId(driverOpenId);
        orderPayFlowEntity.setPayerAccount(driverOpenId);

        orderPayFlowEntity.setPayeeId("mmy-fta-2-driver-deposit");
        orderPayFlowEntity.setPayeeAccount("mmy-fta-2-driver-deposit");

        orderPayFlowEntity.setPayerAmount(deposit);
        orderPayFlowEntity.setPayeeAmount(deposit);

        orderPayFlowEntity.setCreateTime(new Date());
        return orderPayFlowDao.insertSelective(orderPayFlowEntity);
    }

    @Override
    public PrePayCargoFeeResponse prePayCargoFeeByShipper(PrePayCargoFeeRequest payCargoFeeRequest) {
        PrePayCargoFeeResponse prePayCargoFeeResponse = new PrePayCargoFeeResponse();

        ShipperInterestsDTO shipperInterestsDTO = couponService.queryShipperCoupon(payCargoFeeRequest.getOpenId());

        log.info("couponService.queryShipperCoupon-rpc-返回-shipperInterestsDTO：{}",shipperInterestsDTO);

        prePayCargoFeeResponse.setCoupons(shipperInterestsDTO.getCoupons());

        Integer cargoFee = orderDao.queryOrderDetail(payCargoFeeRequest.getOrderNumber()).getTotalFreightAmount();
        prePayCargoFeeResponse.setCargoFee(cargoFee);

        return prePayCargoFeeResponse;
    }

    @Override
    public PayCargoFeeResponse payCargoFeeByShipper(PayCargoFeeRequest payCargoFeeRequest) throws IOException {
        PayCargoFeeResponse payCargoFeeResponse = new PayCargoFeeResponse();
        //check amount
        boolean check = true;

        if(check){
            //使用优惠券
            //update order_status
            //insert pay_flow
            //back deposit
            //payFeeToDriver

            if (payCargoFeeRequest.getPreferenceType() == 1 || payCargoFeeRequest.getPreferenceType() == 2 ) {
                if(Objects.nonNull(payCargoFeeRequest.getCouponId())){
                    couponService.useCoupon(Long.valueOf(payCargoFeeRequest.getCouponId()));
                }
            }



            //update order_status
            int res = orderService.receiveOrderByShipper(new ReceiveOrderRequest(payCargoFeeRequest.getOpenId(),payCargoFeeRequest.getOrderNumber()));

            if(res == 1){
                //insert pay_flow
                int res2 = payCargoFeeByShipper(payCargoFeeRequest.getOrderNumber(),payCargoFeeRequest.getOpenId(),
                        payCargoFeeRequest.getPayAmount());

                if(res2 == 1){
                    //back deposit
                    Integer isBackDeposit = orderDao.queryOrderDetail(payCargoFeeRequest.getOrderNumber()).getIsBackDeposit();
                    if(isBackDeposit == 1){
                        // 退 pay_flow

                    }else {
                        // 不退 pay_flow

                    }
                    payCargoFeeResponse.setSuccess(true);
                    return payCargoFeeResponse;
                }else {
                    payCargoFeeResponse.setSuccess(false);
                    return payCargoFeeResponse;
                }

            }else {
                payCargoFeeResponse.setSuccess(false);
                return payCargoFeeResponse;
            }
        }else {
            payCargoFeeResponse.setSuccess(false);
            return payCargoFeeResponse;
        }
    }


    public int payCargoFeeByShipper(String orderNumber, String openId, Integer payAmount){
        OrderPayFlowEntity orderPayFlowEntity = new OrderPayFlowEntity();

        orderPayFlowEntity.setOrderId(orderNumber);

        String payId =  String.valueOf(new SnowflakeIdUtils(3, 1).nextId());
        orderPayFlowEntity.setPayId(payId);

        orderPayFlowEntity.setFeeType(2);

        orderPayFlowEntity.setPayerId(openId);
        orderPayFlowEntity.setPayerAccount(openId);

        orderPayFlowEntity.setPayeeId("mmy-fta-2-driver-deposit");
        orderPayFlowEntity.setPayeeAccount("mmy-fta-2-driver-deposit");

        orderPayFlowEntity.setPayerAmount(payAmount);
        orderPayFlowEntity.setPayeeAmount(payAmount);

        orderPayFlowEntity.setTotalAmount(payAmount);

        orderPayFlowEntity.setCreateTime(new Date());
        orderPayFlowEntity.setUpdateTime(new Date());

        return orderPayFlowDao.insert(orderPayFlowEntity);
    }

}
